from fastapi import APIRouter, Depends

from apps.functional import cruds, schemas
from apps.functional.params.caselib import CaselibParams
from core.auth import Auth, FullAdminAuth
from core.dependencies import IdList
from core.response import SuccessResponse

router = APIRouter(prefix="/caselib")


@router.get("/list", summary="获取用例库列表")
async def list_caselibs(
        params: CaselibParams = Depends(),
        auth: Auth = Depends(FullAdminAuth(permissions=["functional.caselib.list"]))
):
    datas, count, follows = await cruds.CaseLibDal(auth.db).get_caselibs(auth.user.id, **params.dict())
    return SuccessResponse(datas, count=count, follows=follows)


@router.post("/create", summary="创建用例库")
async def create_caselib(
        data: schemas.Caselib,
        auth: Auth = Depends(FullAdminAuth(permissions=["functional.caselib.create"]))
):
    data.create_user_id = auth.user.id
    return SuccessResponse(
        await cruds.CaseLibDal(auth.db).create_data(data=data),
        msg="创建成功"
    )


@router.put("/update/{data_id}", summary="更新用例库")
async def update_caselib(
        data_id: int,
        data: schemas.Caselib,
        auth: Auth = Depends(FullAdminAuth(permissions=["functional.caselib.update"]))
):
    return SuccessResponse(
        await cruds.CaseLibDal(auth.db).put_data(data_id, data),
        msg="修改成功"
    )


@router.delete("/delete", summary="删除用例库")
async def delete_caselib(
        ids: IdList = Depends(),
        auth: Auth = Depends(FullAdminAuth(permissions=["functional.caselib.delete"]))
):
    return SuccessResponse(
        await cruds.CaseLibDal(auth.db).delete_datas(ids.ids, v_soft=True),
        msg="删除成功"
    )


@router.post("/follow", summary="关注/取消关注用例库")
async def follow_caselib(
        data: schemas.CaselibFollowIn,
        auth: Auth = Depends(FullAdminAuth())
):
    user_id = auth.user.id
    return SuccessResponse(
        await cruds.CaseLibDal(auth.db).follow(data.caselib_id, user_id, data.follow),
        msg="关注成功" if data.follow else "取消关注成功"
    )


@router.get("/options", summary="获取用例库列表，选择用")
async def list_caselib_options(
        auth: Auth = Depends(FullAdminAuth())
):
    return SuccessResponse(await cruds.CaseLibDal(auth.db).get_select_options())
